package com.kong.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kong.constant.MessageConstant;
import com.kong.dao.SetmealDao;
import com.kong.entity.PageResult;
import com.kong.pojo.Setmeal;
import com.kong.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * debug 模式下断点未取消进行debug模式启动造成注册速度变慢
 * @author yang2013
 * @data 2020/10/11 13:02
 */
@Service(interfaceClass = SetmealService.class)
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;
    @Override
    public PageResult findByPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        List<Setmeal> setmeals=setmealDao.findByPage(queryString);
        PageInfo pageInfo=new PageInfo(setmeals);
        return new PageResult(pageInfo.getTotal(),setmeals);
    }

    @Transactional
    @Override
    public void add(Setmeal setmeal, Integer[] integers) {
        int effectNum=setmealDao.addSetmeal(setmeal);
        if (effectNum<=0){
            throw new RuntimeException();
        }
        /**
         * 将检查组对应的检查项插入中间表
         */
        addRSList(setmeal,integers);
        //生成静态页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        List<Setmeal> all = setmealDao.findAll();
        //生成套餐静态页面
        generateMobileSetmealListHtml(all);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(all);
    }

    private void generateMobileSetmealDetailHtml(List<Setmeal> all) {
        if (all!=null && all.size()>0) {
            for (Setmeal setmeal : all) {
                Map map=new HashMap();
                Setmeal byId = setmealDao.findById(setmeal.getId());
                map.put("setmeal",byId);
                String outputName="setmeal_detail"+setmeal.getId()+".html";
                generateMobileCommonMethod("mobile_setmeal_detail.ftl",map,outputName);
            }
        }
    }

    private void generateMobileSetmealListHtml(List<Setmeal> all) {
        if (all.size()>0 && all!=null) {
            Map map = new HashMap(0);
            map.put("setmealList",all);
            String name="setmeal.html";
            generateMobileCommonMethod("mobile_setmeal.ftl",map,name);
        }
    }

    private void generateMobileCommonMethod(String mobileName,Map map, String name) {
        Writer out=null;
        try {
            //获取到容器中的配置对象对象
            Configuration configuration = freeMarkerConfigurer.getConfiguration();
            //获取到模板
            Template template = configuration.getTemplate(mobileName);
            String outputFilename=outPutPath+"/"+name;
            //创建输出对象  使用字符缓冲区的流可以一次读一行 效率更高
            out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputFilename))));
            //生成静态html页面
            template.process(map,out);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out !=null){
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    /**
     * 插入套餐和检查组的中间表
     * @param setmeal
     * @param integers
     */
    private void addRSList(Setmeal setmeal, Integer[] integers) {
        if (integers!=null){
            List<Map> mapList=new ArrayList<>();
            for (Integer checkGroupId : integers) {
                Map map=new HashMap();
                map.put("setmealId",setmeal.getId());
                map.put("checkGroupId",checkGroupId);
                mapList.add(map);
            }
            setmealDao.addRSTable(mapList);
        }
    }


    @Override
    public List<Integer> findCheckGroupIds(Integer id) {
        return setmealDao.findCheckGroupIds(id);
    }

    @Override
    public void updateSetmeal(Setmeal setmeal, Integer[] integers) {
        //删除原有的中间表中检查组对应的信息
        setmealDao.deleteRSBySetmealId(setmeal.getId());
        //更新检查组的信息
        setmealDao.updateSetmeal(setmeal);
        //添加中间表信息
        addRSList(setmeal,integers);
    }

    @Override
    public void deleteById(Integer id) {
         /*
        判断检查组检查项
         */
        int count=setmealDao.countRSMemberById(id);
        if (count>0){
            throw new RuntimeException(MessageConstant.DELETE_CHECKITEM_FAIL2);
        }
        /*
        判断检查组和套餐是否有关联
         */
        int count1=setmealDao.countBySetmealCheckGroupById(id);
        if (count1>0){
            throw new RuntimeException(MessageConstant.DELETE_CHECKGROUP_FAIL3);
        }
        setmealDao.deleteById(id);
    }

    @Override
    public Setmeal findById(Integer setmealId) {
        return setmealDao.findById(setmealId);
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }


}
